using Admin.NET.Core;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DataEncryption;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Magicodes.ExporterAndImporter.Excel;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml;
using System.Data;
using System.Reactive.Joins;
using Yitter.IdGenerator;

namespace Admin.NET.Application
{
    /// <summary>
    /// 巡检车管理
    /// </summary>    
    [Route("api")]
    [ApiDescriptionSettings("路网信息", Name = "RoadManager", Order = 100)]
    public class RoadService : IDynamicApiController, IRoadService, IScoped
    {


       
        /// 获取所有计划列表
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpGet("road/getRoadlist")]

        public async Task<object> GetRoadListAll()
        {
            List<Road> list = Db.GetRepository<Road>().AsQueryable().Adapt<List<Road>>();
            return list;
        }



      

        [HttpPost("road/addroad")]

        public async Task<object> PostAddRoad(Roadinput road)
        {
            var en = Db.GetRepository<Road>().FirstOrDefault(s => s.Name == road.Name, false);
            if (en != null)
                throw Oops.Oh("计划名称已存在，请重新输入！");
            Road roadInfo = road.Adapt<Road>();

            Db.GetRepository<Road>().InsertNow(roadInfo);
            return "添加成功";
        }
        [HttpPost("road/addoreditroad")]

        public async Task<object> PostRoadAddorEdit(Roadinput road)
        {
            Road roadInfo = Db.GetRepository<Road>().FirstOrDefault(x => x.Id == road.Id, tracking: false);
            if (roadInfo != null)
            {
                return await PostRoadEdit(road);
            }
            else
            {
                return await PostAddRoad(road);
            }
        }
        [HttpPost("road/editroad")]

        public async Task<object> PostRoadEdit(Roadinput road)
        {
            Road roadInfo = road.Adapt<Road>();
            var en = Db.GetRepository<Road>().FirstOrDefault(s => s.Name == road.Name && s.Id != roadInfo.Id, false);
            if (en != null)
                throw Oops.Oh("计划名称已存在，请重新输入！");
            Db.GetRepository<Road>().UpdateInclude(roadInfo, new[] { nameof(roadInfo.Name)
                    , nameof(roadInfo.startPoint)
                    ,nameof(roadInfo.endPoint)
                    , nameof(roadInfo.routePaths)
            , nameof(roadInfo.startzh)
            , nameof(roadInfo.endzh)
            });
            return "修改成功";
        }
        [HttpGet("road/getRoadDetail")]

        public async Task<object> GetRoadDetail(long id)
        {
            Road road = Db.GetRepository<Road>().FirstOrDefault(s => s.Id == id, false);

            return road;
        }
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("road/uploadfile")]
        public async Task<string> UploadFileDefault(List<IFormFile> files)
        {
            if (files == null || files.Count == 0)
            {
                return "No file uploaded";
            }

            // 设置文件上传的目标路径
            var uploadPath = Path.Combine(Directory.GetCurrentDirectory(), "uploads");

            // 确保目标路径存在，如果不存在则创建
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            foreach (var file in files)
            {
                // 根据文件名生成一个唯一的文件名
                var uniqueFileName = Guid.NewGuid().ToString() + "_" + file.FileName;

                // 构建文件的完整路径
                var filePath = Path.Combine(uploadPath, uniqueFileName);

                // 保存文件到磁盘
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }

                List<Road> road = ImportExcelData(filePath);
                Db.GetRepository<Road>().InsertNow(road);

                //存入数据库

            }

            //

            return "File uploaded successfully";
        }


        public List<Road> ImportExcelData(string filePath)
        {
            var roads = new List<Road>();
            using (var package = new ExcelPackage(new System.IO.FileInfo(filePath)))
            {
                var worksheet = package.Workbook.Worksheets[1]; // 假设要读取第一个工作表
                var rows = worksheet.Dimension.Rows;
                for (int row = 3; row <= rows; row++) // 假设数据从第二行开始
                {
                    var road = new Road
                    {
                        unit = worksheet.Cells[row, 2].Value?.ToString(),
                        unit1 = worksheet.Cells[row, 3].Value?.ToString(),
                        lineno = worksheet.Cells[row, 4].Value?.ToString(),
                        linename = worksheet.Cells[row, 5].Value?.ToString(),
                        Name = worksheet.Cells[row, 6].Value?.ToString(),
                        skilllevel = worksheet.Cells[row, 7].Value?.ToString(),
                        roadtype = worksheet.Cells[row, 8].Value?.ToString(),
                        startzh = worksheet.Cells[row, 9].Value?.ToString(),
                        endzh = worksheet.Cells[row, 10].Value?.ToString(),
                        length = worksheet.Cells[row, 11].Value?.ToString(),
                        CarNum = worksheet.Cells[row, 12].Value?.ToString(),
                        roadwith = worksheet.Cells[row, 13].Value?.ToString(),
                        speed = worksheet.Cells[row, 14].Value?.ToString(),
                        roadage = worksheet.Cells[row, 15].Value?.ToString(),
                        operationtime = worksheet.Cells[row, 16].Value?.ToString(),
                        filepath = filePath,
                    };
                    roads.Add(road);
                }
                // 将数据插入数据库
            }
            return roads;
        }

        public Task<string> UploadFileDefault(IFormFile file)
        {
            throw new NotImplementedException();
        }
    }




}